package com.example.fmgidsprototype;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.example.fmgidsprototype.data.DataManager;
import com.example.fmgidsprototype.data.VenueCategoryKey;
import com.example.fmgidsprototype.model.Category;
import com.example.fmgidsprototype.model.Review;
import com.example.fmgidsprototype.model.Venue;
import com.example.fmgidsprototype.model.VenueLocation;

public class ReviewJsonReader {

	private BufferedReader bufferedReader;
	private FileReader fileReader;
	private InputStream stream;
	private String jsonString;
	private FmGidsPrototypeApp app;
	private DataManager dm;
	
	public ReviewJsonReader(InputStream stream, DataManager dm){
		this.stream = stream;
		this.dm = dm;
	}
	
	private String readFile(){
		String line = null;
		StringBuilder sb = new StringBuilder();
		bufferedReader = null;
		fileReader = null;

		try{
			bufferedReader = new BufferedReader(new InputStreamReader(stream));
			while((line = bufferedReader.readLine()) != null){
				sb.append(line + "\n");
			}
		}
		catch(IOException ioe){
			ioe.printStackTrace();
		}
		return sb.toString();
	}
	
	public void writeToDb(){
		JSONObject jObject = null;
		List<Review> reviewList = new ArrayList<Review>();
		try{
			jObject = new JSONObject(this.readFile());
			//first get all reviews
			JSONArray reviewArray = jObject.getJSONArray("review");
			//now pick them one by one and for each one...
			for(int i = 0; i < reviewArray.length(); i++){
				JSONObject reviewObject = reviewArray.getJSONObject(i);
				//create model object
				Review currentReview = new Review(
					reviewObject.getLong("venue"),
					reviewObject.getString("comment"),
					reviewObject.getLong("timestamp"),
					reviewObject.getString("username")
				);
				reviewList.add(currentReview);
			}
		}
		catch(JSONException jse){
			jse.printStackTrace();
		}
		Log.d("REVLISTSIZE", "size is: " + reviewList.size());
		//now let's write this shit to the db!
		for(Review review : reviewList){
			//insert review
			if(dm.updateReview(review) <= 0)
				dm.saveReview(review);
		}
	}
	
}
